<template>
    <div class="testcorpper">
        <!-- <group :title="title==null?'附件':title"> -->
            <div style="padding: 0 3vw">
                <div class="image-choose">
                    <div v-for="(item,index) in picslist" :key="index" style="float: left;position: relative;" >
                        <img :src="item.src" @click="showImgPreview(index)">
						<span class="close_picture"  @click="removeImg('0',index,item.fileUrl)">
							<img src="../../assets/images/icon/closePicture.png" style="width:12px;height:12px" alt="">
						</span>
                        <!-- <icon type="cancel" style="position: absolute;right: -8px;top: -6px;"  @click.native="removeImg('0',index,item.fileUrl)" ></icon> -->
                    </div>
					<div v-for="(vitem,vindex) in videolist" :key="vindex" style="float: left;position: relative;" >
					    <img :src="vitem.msrc"  @click="openMedia(1,vitem)">
					    <icon type="cancel" style="position: absolute;right: -8px;top: -6px;"  @click.native="removeImg('1',vindex,vitem.fileUrl)" ></icon>
					</div>
					<div v-for="(aitem,aindex) in audiolist" :key="aindex" style="float: left;position: relative;" >
					    <img :src="aitem.msrc"  @click="openMedia(2,aitem)">
					    <icon type="cancel" style="position: absolute;right: -8px;top: -6px;"  @click.native="removeImg('2',aindex,aitem.fileUrl)" ></icon>
					</div>
                    <div v-if="videolist.length+audiolist.length+picslist.length<limitSize" class="add-image" @click="changeFile">
                         <!-- <input id="file_input"
                            ref="takepicture"
                            style="display: none"
                            @change="getFile"
                            type="file"
                            accept="image/*"
                            capture="camera"
                            multiple="multiple"
                        > -->
						附件
                        <!-- <i class="icon ion-plus-round "></i> -->
                    </div>
                </div>
            </div>
        <!-- </group> -->
        <previewer :list="picslist" ref="preview" :options="options"></previewer>
		<actionsheet  v-model="showSelect" :menus="menuSelect" theme="android" @on-click-menu="clickMenu" @on-after-hide="afterHide" @on-after-show="afterShow">
    </actionsheet>
    </div>
</template>
<script>
import { TransferDom, Actionsheet,Icon, Group, Previewer } from "vux";
let formData = new FormData();
export default {
	props: ["title","typeflag","upNumber"],
    directives: {
		TransferDom
	},
	components: { Icon, Group, Previewer,Actionsheet },
    data() {
        return {
            fileList: [], //原始附件数组
            picslist: [], //放大附件数组
			videolist:[],
			audiolist:[],
			uplist:[],
			upvideolist:[],
			showSelect:false,
			limitSize:5,
			menuSelect:{
				menu1: '图片',
				menu2: '视频',
				menu3: '音频'
			  },
			options: {
				  isClickableElement: function (el) {
					return /previewer-delete-icon/.test(el.className)
				  }
				},
        };
    },
    methods: {
        removeImg(type,index,fileUrl) {
            let vm = this;
			/* let file_input= document.getElementById("file_input");
			console.log(file_input.currentTarget)
			console.log(file_input.outerHTML) */
			console.log(type+"====>"+index+"===>"+fileUrl)
            let contentStr="";
			if(type=="0"){
				contentStr="确认删除该图片？";
			}else if(type=="1"){
				contentStr="确认删除该视频？";
			}else if(type=="2"){
				contentStr="确认删除该录音？";
			}
			console.log("contentStr===>"+contentStr);
			vm.$vux.confirm.show({
                title: "删除",
                content:contentStr,
                onConfirm() {
					console.log(JSON.stringify(vm.picslist))
					console.log(JSON.stringify(vm.fileList))
					if(type=="0"){
						console.log("del picslist fileList")
						vm.picslist.splice(index, 1);
						vm.fileList.splice(index, 1);
						console.log("del picslist fileList success")
					}else if(type=="1"){
						vm.videolist.splice(index, 1);
					}else if(type=="2"){
						vm.audiolist.splice(index, 1);
					}
					try{
						console.log("param==>delete img success "+fileUrl)
						window.android.removePhoto(fileUrl)
					}catch(e){
						console.log("param==> delete img error")
						//TODO handle the exception
					}
					/* let fileArr=new FileList();
					console.log(file_input.files.length)
					for(var i=0;i<file_input.files.length;i++){
						if(index!=i){
							//file_input.files.baoremove(index)
							fileArr.push(file_input.files[i]);
						}
					}
					debugger */
					/* FileList
					debugger */
					//fileArr.splice(index, 1);
					//file_input.files = fileArr;
                    vm.postBack();
                }
            });
        },
		openMedia(type,item){
			console.log("type==>"+type+"==>")
			console.log(item)
			try{
				window.android.openlocalFile(item.fileUrl);
			}catch(e){
				console.log("param==> open Gallery error")
				//TODO handle the exception
			}
		},
		clickMenu(item){
			console.log("param==> item is ==>"+item);
			try{
				console.log("close menu...")
				this.showSelect=false;
				if(item&&item=='menu1'){
					//打开android相册功能
					window.android.openGallery(1,this.limitSize);
				}else if(item&&item=='menu2'){
					//打开android视频功能
					window.android.openGallery(2,this.limitSize);
				}else if(item&&item=='menu3'){
					//打开android录音功能
					window.android.openGallery(3,this.limitSize);
				}else{
					console.log("param==> item is error ==>"+item);
				}
				
				
			}catch(e){
				console.log("param==> open Gallery error")
				//TODO handle the exception
			}
		},
		afterHide(){
			console.log("afterHide")
		},
		afterShow(){
			console.log("afterShow")
		},
        changeFile: function() {
			//项目需求关闭组件弹出
			return;
            //this.$refs.takepicture.dispatchEvent(new MouseEvent("click"));
			let _this=this;
			let listsize=_this.uplist.length+_this.upvideolist.length;
			_this.uplist=[];
			_this.upvideolist=[];
			if(listsize>=_this.limitSize){
				this.$vux.toast.show({
				  text:"附件个数不能大于"+_this.limitSize+"个",
				  type:"cancel"
				})
			}else{
				try{
					//打开android相册功能
					//window.android.openGallery(1,9);
					if(this.typeflag){
						this.showSelect=true;
					}else{
						window.android.openGallery(1,this.limitSize);
					}
				}catch(e){
					console.log("param==> open Gallery error")
					//TODO handle the exception
				}
			}
			
        },
		getMedias(type,medias){
			let _this=this;
			//console.log("param==>"+medias);
			console.log("param==>"+JSON.stringify(medias));
			console.log("type==>"+type+"=typeflag==>"+_this.typeflag);
			//如果有值需要传图片视频与录音文件并由android进行上传操作
			if(_this.typeflag){
				
				if(type=="1"){
					for(var i=0;i<_this.picslist.length;i++){
						let item=_this.picslist[i];
						try{
							console.log("param==>delete img success "+item.fileUrl)
							window.android.removePhoto(item.fileUrl)
						}catch(e){
							console.log("param==> delete img error")
							//TODO handle the exception
						}
					}
					_this.picslist=[];
					let listsize=_this.videolist.length+_this.audiolist.length;
					if(medias&&medias.result){
						console.log("其它数量==>"+listsize+"==>android数据==>"+medias.result.length)
						if(listsize+medias.result.length>_this.limitSize){
							_this.$vux.toast.show({
							  text:"附件个数不能大于"+_this.limitSize+"个",
							  type:"cancel"
							})
						}else{
							for (var index in medias.result) {
								let item=medias.result[index];
								console.log("param==>file://"+item)
								 let base64;
								try{
									base64=window.android.file2Base64(item)
								}catch(e){
									base64="base64isnull";
								}
								if(base64!="base64isnull"){
									_this.picslist.push({
										msrc:"data:image/png;base64,"+base64,
										src: "data:image/png;base64,"+base64,
										fileUrl:item
									})
									
								}
							}
						}
						
					}
				}else if(type=="2"){
					for(var i=0;i<_this.videolist.length;i++){
						let item=_this.videolist[i];
						try{
							console.log("param==>delete img success "+item.fileUrl)
							window.android.removePhoto(item.fileUrl)
						}catch(e){
							console.log("param==> delete img error")
							//TODO handle the exception
						}
					}
					_this.videolist=[];
					let listsize=_this.picslist.length+_this.audiolist.length;
					if(medias&&medias.result){
						console.log("其它数量==>"+listsize+"==>android数据==>"+medias.result.length)
						if(listsize+medias.result.length>_this.limitSize){
							_this.$vux.toast.show({
							  text:"附件个数不能大于"+_this.limitSize+"个",
							  type:"cancel"
							})
						}else{
							for (var index in medias.result) {
								let item=medias.result[index];
								_this.videolist.push({
									msrc:require('../../assets/images/icon/video.png'),
									fileUrl:item
								})
							}
						}
						
					}
				}else if(type=="3"){
					for(var i=0;i<_this.audiolist.length;i++){
						let item=_this.audiolist[i];
						try{
							console.log("param==>delete img success "+item.fileUrl)
							window.android.removePhoto(item.fileUrl)
						}catch(e){
							console.log("param==> delete img error")
							//TODO handle the exception
						}
					}
					_this.audiolist=[];
					let listsize=_this.picslist.length+_this.videolist.length;
					if(medias&&medias.result){
						console.log("其它数量==>"+listsize+"==>android数据==>"+medias.result.length)
						if(listsize+medias.result.length>_this.limitSize){
							_this.$vux.toast.show({
							  text:"附件个数不能大于"+_this.limitSize+"个",
							  type:"cancel"
							})
						}else{
							for (var index in medias.result) {
								let item=medias.result[index];
								_this.audiolist.push({
									msrc:require('../../assets/images/icon/audio.png'),
									fileUrl:item
								})
							}
						}
						
					}
				}
				_this.postBack();
			}else{//执行原始上传操作
				_this.picslist=[];
				_this.fileList=[];
				if(medias&&medias.result){
					if(medias.result.length>_this.limitSize){
						_this.$vux.toast.show({
						  text:"附件个数不能大于"+_this.limitSize+"个",
						  type:"cancel"
						})
					}else{
						for (var index in medias.result) {
							let item=medias.result[index];
							console.log("param==>file://"+item)
							 let base64;
							try{
								base64=window.android.file2Base64(item)
							}catch(e){
								base64="base64isnull";
							}
							if(base64!="base64isnull"){
								_this.picslist.push({
									msrc:"data:image/png;base64,"+base64,
									src: "data:image/png;base64,"+base64,
									fileUrl:item
								})
								console.log("item name===>"+item.substr(item.length-7,item.length))
								let fileobj=_this.dataURLtoFile("data:image/png;base64,"+base64,item.substr(item.length-7,item.length))
								_this.fileList.push(fileobj)
							}
							// _this.picslist.push({
							// 	msrc: "file://"+item,
							// 	src: "file://"+item
							// })
						}
					}
					
					_this.postBack();
				}
			}
			
		},
		setFileObj(fileObj){
			console.log("come in")
				console.log(fileObj)
				console.log("fileObj==>")
				//console.log(JSON.stringify(fileObj))
				this.fileList.push(fileObj)
			
		},
        showImgPreview(index) {
			//this.preview
            //点击图片放大
            this.$refs.preview.show(index);
		},
		getCurrentItem(){
			let itemIndex=this.$refs.preview.getCurrentIndex();
			console.log("currindex==>"+itemIndex)
			console.log(this.$refs.preview.photoswipe)
		},
		closePreview(){
			this.$refs.preview.close();
		},
		GetAriaHidden(){
			let ariaHidden;
			try {
				ariaHidden=document.querySelector(".vux-previewer").getAttribute('aria-hidden');
				if(ariaHidden&&ariaHidden=='false'){
					ariaHidden=false;
				}else{
					ariaHidden=true;
				}
			} catch (error) {
				console.warn(error)
				ariaHidden=true;
			}
			return ariaHidden;
		},
        getFile: function(e) {
            //附件数据处理
			console.log(e)
            let vm = this;
            try {
                let files = e.currentTarget.files;
                if (files.length > 0) {
                   /* for (let i = 0; i < files.length; i++) {
                        if (vm.fileList.length < 5) {
                            vm.fileList.push(files[i]);
                            let img = window.URL.createObjectURL(files[i]);
                            vm.picslist.push({
                                msrc: img,
                                src: img
                            });
                        }
                    } */
					 vm.imgList = [];
					let newfiles=[];
					for(let k=0;k<files.length;k++){
						lrz(files[k], {
							width : 500,
							quality: 1    //自定义使用压缩方式
						}).then(function(rst) {
							console.log(rst)
							vm.picslist.push({msrc:rst.base64,src:rst.base64});
							vm.imgList.push(rst.base64);
							newfiles.push(rst.file)
							let fileobj= vm.dataURLtoFile(rst.base64,"fff")
							console.log(fileobj)
								//成功时执行
						}).catch(function(error) {
								//失败时执行
						}).always(function() {
								//不管成功或失败，都会执行
						})
					}
					vm.fileList = newfiles;
					
                    vm.postBack();
                }
            } catch (e) {
                alert(e);
            }
        },
		//将base64转换为文件对象
		 dataURLtoFile(dataurl, filename) {
			var arr = dataurl.split(',');
			console.log(arr[0])
			var mime = arr[0].match(/:(.*?);/)[1];
			var bstr = atob(arr[1]);
			var n = bstr.length; 
			console.log("文件大小=="+n)
			var u8arr = new Uint8Array(n);
			while(n--){
					u8arr[n] = bstr.charCodeAt(n);
			}
			let file=new File([u8arr], filename, {type:mime});
			console.log("filename==>"+file.name)
			//转换成file对象
			return file;
			//转换成成blob对象
			//return new Blob([u8arr],{type:mime});
		},
		//将图片转换为Base64
		 getImgToBase64(url,callback){
		  var canvas = document.createElement('canvas'),
		  ctx = canvas.getContext('2d'),
		  img = new Image;
		  img.crossOrigin = 'Anonymous';
		  img.onload = function(){
			canvas.height = img.height;
			canvas.width = img.width;
			ctx.drawImage(img,0,0);
			var dataURL = canvas.toDataURL('image/png');
			callback(dataURL);
			canvas = null;
		  };
		  img.src = url;
		},
        postBack() {
			let _this=this;
			_this.uplist=[];
			_this.upvideolist=[];
			//重新更新要上传的数组
			_this.picslist.forEach(function(item,index){
				_this.uplist.push(item.fileUrl);
			})
			_this.videolist.forEach(function(item,index){
				_this.upvideolist.push(item.fileUrl);
			})
			_this.audiolist.forEach(function(item,index){
				_this.uplist.push(item.fileUrl);
			})
            //数据回传
            this.$emit("fliws", this.fileList);
			console.log("更新字符串图片="+JSON.stringify(this.uplist))
			console.log("更新字符串视频="+JSON.stringify(this.upvideolist))
			let paramObj={"uplist":this.uplist,"upvideolist":this.upvideolist}
			//paramObj={"uplist":["/storage/emulated/0/1582544844680431.jpg"],"upvideolist":[]}
			console.log("set up list ==>"+JSON.stringify(paramObj))
			this.$emit("uplist",paramObj)
        },clearPhoto(){
			try{
				window.android.clearPhotos();
			}catch(e){
				console.log("param==>clearphotos error");
				//TODO handle the exception
			}
		}
    },
    created: function() {
		if(this.upNumber){
			this.limitSize=parseInt(this.upNumber);
		}
		//this.picslist=[{"src":"http://118.190.86.214:8080/macau_public/yq/1.png"},{"src":"http://118.190.86.214:8080/macau_public/yq/1.png"},{"src":"http://118.190.86.214:8080/macau_public/yq/1.png"},{"src":"http://118.190.86.214:8080/macau_public/yq/1.png"}]
	},
	mounted:function() {
		let _this=this;
    	this.clearPhoto();
		window.getMedias=this.getMedias;
		window.setFileObj=this.setFileObj;
		// let intervalint= setInterval(() => {
		// 	console.log(_this.GetAriaHidden())
		// }, 3000);
		// setTimeout(() => {
		// 	clearInterval(intervalint)
		// }, 15000);
	}
};
</script>
<style  scoped>
.testcorpper .image-choose {
    margin: 10px auto;
	overflow: hidden;
}
.testcorpper .image-choose .close_picture{
	width: 15px;
	height: 15px;
	display: block;
	position: absolute;
	    top: 4px;
    right: 5px;
    opacity: .9;
	
}
.close_picture img{
	width: 100%;

}
.testcorpper .image-choose img {
    margin-top: 5px;
    margin-left: .7vw;
	width: 18vw;
    height: 16vw;
    vertical-align: top;
    border-radius: 6px;
}

.testcorpper .image-choose .add-image {
    display: inline-block;
    margin-top: 5px;
    margin-left: 1vw;
    width: 18vw;
       height: 16vw;
    line-height: 16vw;
	color: #20a0e7;
	font-size: 16px;
	/* background: #eee; */
	border-radius: 6px;
	text-align: center;
	border: dashed 1px #1b9fe7;
}

.testcorpper .image-choose .add-image .iconfont {
    font-size: 36px;
    color: #ccc;
}
</style>
<style>
.testcorpper .weui-cells:before {
    border-top: none;
}
</style>

